import { actionDebounce, toPage } from '@/utils/mpHelper'
import type { MessageMappings, OTAHelper, OTAHelperConfigOptions } from './types'
import type { WS } from '@/utils/socket/types'
import { WebsocketManager } from '@/utils/socket/WebsocketManager'
import { useWebsocketListener } from '@/utils/socket/WebSocketHandlerImp'
import {
  COMMON_STATUS_WIFIOTASTATUS,
  COMMON_SETTING_WIFIOTA_CONFIRM,
  COMMON_SETTING_WIFIOTA_CONFIRM_ON,
} from '@/constants/Command'
import { setSettingByNokeySettings, getAllSetting, type ApplianceSettingDes } from '@/api/appliance'
import i18n from '@/i18n'

export default class RefrigeratorBOtaHelper implements OTAHelper {
  configOptions!: OTAHelperConfigOptions

  upgradeDetected = ref(false) // 是否检测到升级
  remoteUpgradeSupported = ref(true) // 是否支持小程序远程升级
  upgradingModalVisible = ref(false) // 是否显示【固件升级中】弹框
  successModalVisible = ref(false) // 是否显示【固件已升级至最新版本】确认框
  retryModalVisible = ref(false) // 是否显示【网络异常，请重试】弹框

  private mcuStatus = ref(0)
  upgradingMessage = ref('')

  /**
   * 收到升级成功的event时
   *  - [可选] 不设置时 不处理acknowledge
   *  - auto: 自动下发acknowledge，并弹出toast提醒用户升级成功
   *  - manual: 显示【固件已升级至最新版本】确认框，需要等待用户手动点击【知道了】按钮后再下发acknowledge
   */
  private successAcknowledge?: 'auto' | 'manual'

  constructor(options: OTAHelperConfigOptions) {
    this.configOptions = options
    this.addMessageListener()
    this.initBindings(options.scene as string)
  }

  destroy(): void {
    this.removeMessageListener()
  }

  get haId() {
    return this.configOptions.haId
  }

  async toUpgradePage() {
    const options = this.configOptions
    await toPage('/pages/appliance/settings/ota/firmwareUpdate', {
      brand: options.brand,
      type: options.type,
      vib: options.vib,
      haId: options.haId,
    })
  }
  hideAllModal() {
    this.upgradingModalVisible.value = false
    this.successModalVisible.value = false
    this.retryModalVisible.value = false
  }
  checkUpgrade = actionDebounce({
    delay: 3000,
    call: async () => {
      this.upgradeDetected.value = false
      const res = await getAllSetting(this.haId, true)
      const { settings } = res.data
      this.handleAllSetting(settings)
    },
  })
  allowUpgrade = actionDebounce({
    delay: 3000,
    call: async () => {
      const res = await setSettingByNokeySettings(
        this.haId,
        COMMON_SETTING_WIFIOTA_CONFIRM,
        COMMON_SETTING_WIFIOTA_CONFIRM_ON
      )
      if (res.code !== 0) {
        this.retryModalVisible.value = true
      } else {
        this.upgradingModalVisible.value = true
      }
    },
  })
  async acknowledgeSuccessful() {}

  async checkRemoteUpgradeSupported() {}

  private messageListener = (msg: WS.Message) => {
    if (msg.haId !== this.haId || !Array.isArray(msg.items)) return
    msg.items.forEach((item) => {
      if (item.key === COMMON_STATUS_WIFIOTASTATUS) {
        this.mcuStatus.value = Number(item.value)
      }
    })
  }

  private addMessageListener(): void {
    useWebsocketListener(WebsocketManager.instance.oemWebsocket, this.messageListener)
  }
  private removeMessageListener(): void {
    WebsocketManager.instance.oemWebsocket.removeMessageListener(this.messageListener)
  }
  private msgMappings: MessageMappings = [
    { key: COMMON_STATUS_WIFIOTASTATUS, value: '1', handler: () => (this.upgradeDetected.value = true) },
  ]
  private handleMessages(messages: WS.MessageItem[]): void {
    messages.forEach((msg) => {
      const matchedMapping = this.msgMappings.find((mapping) => msg.key === mapping.key && msg.value === mapping.value)
      if (!matchedMapping) return
      matchedMapping.handler.call(this, msg)
    })
  }

  private handleAllSetting(messages: ApplianceSettingDes[]): void {
    messages.forEach((msg) => {
      if (msg.key == COMMON_STATUS_WIFIOTASTATUS) {
        console.error(msg.key)
      }
      const matchedMapping = this.msgMappings.find((mapping) => msg.key == mapping.key && msg.value == mapping.value)
      if (matchedMapping) {
        this.upgradeDetected.value = true
      }

      if (!matchedMapping) return
    })
  }
  private onUpdateAvailableOff() {
    this.hideAllModal()
    this.upgradingModalVisible.value = true
  }
  private async onUpdateSuccessful() {
    this.hideAllModal()

    /**
     * 手动确认固件升级完成
     */
    if (this.successAcknowledge === 'manual') {
      // 弹出提示框，点击【知道了】按钮下发acknowledge
      this.successModalVisible.value = true
      return
    }

    /**
     * 自动确认固件升级完成
     */
    if (this.successAcknowledge === 'auto') {
      // 下发acknowledge 不再提示用户
      this.acknowledgeSuccessful().finally(() => {
        // 显示升级成功Toast
        uni.showToast({
          title: i18n.global.t('Appliance.Settings.FirmwareUpgrade.UpgradeSucess.Toast.Title'),
          icon: 'success',
        })
      })
    }
  }
  private onAcknowledgeComplete() {
    this.hideAllModal()
    // 刷新状态
    this.checkUpgrade()
  }
  private initBindings(scene: string): void {
    watchEffect(async () => {
      switch (this.mcuStatus.value) {
        case WifiOtaStatus.WifiOtaStatusNormal:
          this.upgradingMessage.value = ''
          this.upgradingModalVisible.value = false
          break
        case WifiOtaStatus.WifiOtaStatusDownload:
          if (scene !== 'firmware') return
          this.upgradingMessage.value = '正在下载固件升级包...'
          this.upgradingModalVisible.value = true
          break
        case WifiOtaStatus.WifiOtaStatusReboot:
          if (scene !== 'firmware') return
          this.upgradingMessage.value = '正在重启通信模组...'
          this.upgradingModalVisible.value = true
          break
        case WifiOtaStatus.WifiOtaStatusOTAFinish:
          if (scene !== 'firmware') return
          this.upgradingMessage.value = '升级完成,正在重启通信模组...'
          this.upgradingModalVisible.value = true
          break
        case WifiOtaStatus.WifiOtaStatusOTASuccess:
          this.upgradingModalVisible.value = false
          this.retryModalVisible.value = false
          this.upgradingMessage.value = ''
          if (scene === 'firmware') {
            uni.showToast({
              title: i18n.global.t('Appliance.Settings.FirmwareUpgrade.UpgradeSucess.Toast.Title'),
              icon: 'success',
            })
          } else {
            this.successModalVisible.value = true
          }
          this.upgradeDetected.value = false

          break
        case WifiOtaStatus.WifiOtaStatusOTAFail:
          if (scene !== 'firmware') return
          this.successModalVisible.value = false
          this.upgradingModalVisible.value = false
          this.retryModalVisible.value = true
          this.upgradingMessage.value = ''
          break
        default:
          break
      }
    })
  }
}

export enum WifiOtaStatus {
  WifiOtaStatusNormal = 0, // 无需升级
  WifiOtaStatusNeedUpload = 1, //需要升级
  WifiOtaStatusDownload = 2, // 正在下载
  WifiOtaStatusReboot = 3, // 正在重启
  WifiOtaStatusOTASuccess = 4, // 升级成功
  WifiOtaStatusOTAFail = 5, // 升级失败
  WifiOtaStatusOTAFinish = 6, // 升级完成
}
